/*
 * Copyright Hundsun Technologies Inc. All Rights Reserved.
 */

package seqcenter

import (
	"errors"

	"github.com/golang/protobuf/proto"
	"hundsun.com/hsl/hschain/common/crypto"
	"hundsun.com/hsl/hschain/protos/common"
)

func (m *SaveBlockResponse) clone() *SaveBlockResponse {
	clonedMsg := &SaveBlockResponse{
		StatusCode:    m.StatusCode,
		BlockNumber:   m.BlockNumber,
		BlockHash:     m.BlockHash,
		BlockSequence: m.BlockSequence,
		Signature:     m.Signature,
	}
	return clonedMsg
}

func (m *SaveBlockResponse) marshal() []byte {
	bytes, err := proto.Marshal(m)
	if err != nil {
		panic(err)
	}
	return bytes
}

// Sign SignableMessage接口
func (m *SaveBlockResponse) Sign(keyPair crypto.KeyPair) {
	m.Signature = nil
	signatureBytes, err := keyPair.Sign(m.marshal())
	if err != nil {
		panic(err)
	}
	m.Signature = &common.Signature{
		Algorithm: uint32(keyPair.GetSignatureAlgorithm()),
		PublicKey: keyPair.PublicKey().Bytes(),
		Signature: signatureBytes,
	}
}

// ValidateFormat ...
func (m *SaveBlockResponse) ValidateFormat() error {
	if m.BlockNumber == 0 {
		return errors.New("block number cannot be zero")
	}
	if len(m.BlockHash) == 0 {
		return errors.New("block Hash cannot be empty")
	}
	sig := m.Signature
	if sig == nil || len(sig.Signature) == 0 || len(sig.PublicKey) == 0 {
		return errors.New("format of signature is invalid")
	}
	return nil
}
